package com.project.controllers;

import java.io.StringWriter;
import java.net.URL;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.apache.log4j.Logger;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;

@Controller
@RequestMapping(value="/data")
public class QueryPlanControllerTest {
	protected final Logger log = Logger.getLogger(QueryPlanControllerTest.class);

	@RequestMapping(value="queryplan/*", method = RequestMethod.GET)
	//assuming you have an XML query plan called "example.xml" in the same package 
	//and the XSLT file in the same package 
	public ModelAndView getQueryPlan() {
		//this references the JSP file queryplantest.jsp (viewresolver handles the extension) 
		ModelAndView modelAndView = new ModelAndView("queryplantest");	

		//get path to XSLT file 
		URL xsltURL = getClass().getResource("qp.xslt");
		//get path to XML file 
		URL xmlURL = getClass().getResource("example.xml");
		
		try {
			StringWriter writer = new StringWriter();
			TransformerFactory tFactory = TransformerFactory.newInstance();
			
			//recoverable errors should not be logged 
			tFactory.setAttribute("http://saxon.sf.net/feature/recoveryPolicy", 1);
			tFactory.setAttribute("http://saxon.sf.net/feature/recoveryPolicyName", "recoverSilently");
			
			Transformer transformer = tFactory.newTransformer(
				new javax.xml.transform.stream.StreamSource(
						xsltURL.toString()
				)
			);
			
			//transform XML to HTML and store the text in writer 
			transformer.transform(
				new javax.xml.transform.stream.StreamSource(xmlURL.toString()), 
				new javax.xml.transform.stream.StreamResult(writer)
			);
			
			//add the HTML to the model and view as an object called "retHTML" 
			modelAndView.addObject("retHTML", writer.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//return to the page (queryplantest) 
		return modelAndView; 
	}
}


